<template>
  <div>
    <div class="topBtn">
      <div class="sizeBig"><span>订单排产</span></div>
      <div>
        <el-button @click="init" style="height:39px;" type="primary">查询</el-button>
        <el-button @click="production" type="primary">
          <i class="icon-hand"></i>手动排产
        </el-button>
        <el-button @click="setrule" type="primary">
          <i class="icon-set"></i>排程规则设置
        </el-button>
      </div>
    </div>
    <div class="message">
      <p class="character">订单从商城同步到MES系统后，系统会根据设置好的结单时间加载符合时间要求的订单数据到待排产队列中等待。当达到一定条件后，后台服务会根据设置好的规则创建成一个排程。
        当遇到临时情况需要手动接入生成排程号时，可以启用手动排产。本轮订单不清空，下一轮订单不会加载出来。<span class="skip">查看帮助文档</span></p>
    </div>
    <div class="inputcontent">
      <el-input class="inSearch" placeholder="请输入关键字检索订单" v-model="search"></el-input>
      <div @click="init" class="iconSearch"></div>
      <el-select @change="init" placeholder="状态" v-model="value">
        <el-option
          :key="item.value"
          :label="item.label"
          :value="item.value"
          v-for="item in options">
        </el-option>
      </el-select>
      <!-- <el-select v-model="value1" placeholder="印刷方式">
          <el-option
          v-for="item in options1"
          :key="item.value"
          :label="item.label"
          :value="item.value">
          </el-option>
      </el-select>
      <el-select v-model="value2" placeholder="相纸类型">
          <el-option
          v-for="item in options2"
          :key="item.value"
          :label="item.label"
          :value="item.value">
          </el-option>
      </el-select> -->

      <!-- <div class="time">
          <h4>当前排产的订单时间段为：</h4>
          <span>21:00--10:00</span>
      </div>
      <div class="next">
          <h4>下一波订单数：</h4>
          <span>114</span>
      </div> -->
    </div>
    <div class="table">
      <Table :reset="reset"></Table>
    </div>
    <div class="block">
      <el-pagination
        :current-page="currentPage"
        :page-size="size"
        :page-sizes="[10,20,50,100]"
        :total="TotalNum"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
        layout="total, sizes, prev, pager, next, jumper">
      </el-pagination>
    </div>

    <!-- 手动排产弹出框 -->
    <el-dialog :close-on-click-modal='false' :visible.sync="proDialogVisible" center title="手动排产界面" width="800px">
      <h5>经系统匹配计算，无法获取最优排产方案，请手动选择排产规则：</h5>
      <el-radio-group class="anniu" v-model="radio">
        <el-radio :label="1">规则1xxxxxxx</el-radio>
        <el-radio :label="2">规则2xxxxxxx</el-radio>
        <el-radio :label="3">规则3xxxxxxx</el-radio>
      </el-radio-group>
      <div class="botBtn">
        <el-button @click="proDialogVisible=false">取消</el-button>
        <el-button @click="onSubmit1" type="primary">确定</el-button>
      </div>
      <div class="checkbox">
        <el-checkbox v-model="checked">从下批订单凑单</el-checkbox>
      </div>
    </el-dialog>

    <!-- 排程规则设置弹出框 -->
    <el-dialog :close-on-click-modal='false' :visible.sync="ruleDialogVisible" center

               width="80%"
               title="自动排产规则设置">

      <div style="display: flex;justify-content: flex-end">

        <!--        <el-input clearable style="width:270px ;margin-left: 10px" suffix-icon="el-icon-search"/>-->

        <el-form :inline="true" :model="searchFormData" label-width="85px" ref="searchDataForm" size="small">

          <el-form-item label="产线名" prop="LineName">
            <el-input @keyup.enter.native="searchRequest" clearable icon="el-icon-search"
                      style="width: 200px" v-model="searchFormData.LineName"/>
          </el-form-item>

          <el-form-item label="模版名" prop="BoardModelID">
            <el-select @change="searchRequest" @clear="searchRequest" clearable style="width: 200px"
                       v-model="searchFormData.BoardModelID">
              <el-option :key="item.BoardModelID" :label="item.Name" :value="item.BoardModelID"
                         v-for="(item,index) in  boardModelData"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="线体名" prop="LineId">
            <el-select @change="searchRequest" @clear="searchRequest" clearable style="width: 200px"
                       v-model="searchFormData.LineId">
              <el-option :key="item.LineId" :label="item.Name" :value="item.LineId"
                         v-for="(item,index) in linebodyData"></el-option>
            </el-select>
          </el-form-item>

          <!--       PrintStatus   -->

          <el-button @click="addRule" type="primary">添加规则设置</el-button>
        </el-form>

      </div>
      <Table1 :innerVisible="innerVisible" :ruleData="ruleData" @openEditDialog="openEditDialog"
              ref="ruleForm"></Table1>

      <Pagination :limit.sync="limit" :page.sync="current" :total="total"
                  @pagination="GetAutoProductionPlanList"></Pagination>
      <!--      <div @click="add3" class="add">-->
      <!--        <span class="skip">添加</span>-->
      <!--      </div>-->
      <!--            <div class="anniu">-->
      <!--                <el-button class="fanhui" @click="ruleDialogVisible=false">取消</el-button>-->
      <!--                <el-button type="primary" @click="onSubmit">保存</el-button>-->
      <!--            </div>-->
      <el-dialog
        :close-on-click-modal="false"
        :title="`排程规则${mode==='edit'?'编辑':'新增'}`"
        :visible.sync="innerVisible"
        @closed="addRuleData = {}"
        append-to-body
        width="40%">
        <el-form :model="addRuleData" label-width="100px">
          <el-form-item label="规则名称">
            <el-input v-model="addRuleData.OrderAutoPlanName"></el-input>
          </el-form-item>
          <el-row>
            <el-col :span="12">
              <el-form-item label="排程线体">
                <el-select clearable v-model="addRuleData.LineId">
                  <el-option :key="item.LineId" :label="item.Name" :value="item.LineId"
                             v-for="(item,index) in linebodyData"></el-option>
                </el-select>
                <!--           filterLinebodyData(addRuleData.BoardModelID,)     -->
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="拼版模板">
                <el-select :disabled="!addRuleData.LineId" clearable filterable v-model="addRuleData.BoardModelID">
                  <el-option :key="item.BoardModelID" :label="item.Name" :value="item.BoardModelID"
                             v-for="(item,index) in  getCanSelectBoardList(addRuleData)"></el-option>
                  <!--            boardData      selectBoardList -->
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="最小版数">
                <el-input-number size="mini" v-model="addRuleData.MinNum"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="最大版数">
                <el-input-number size="mini" v-model="addRuleData.MaxNum"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="是否启用">
            <el-switch :active-value="1" :inactive-value="0" v-model="addRuleData.Status"></el-switch>
          </el-form-item>

          <el-form-item label="优先级">
            <!--            <el-select v-model="addRuleData.Priority">-->
            <!--              <el-option :key="item.value" :label="item.label" :value="item.value" v-for="item in options3"></el-option>-->
            <!--            </el-select>-->
            <el-slider
              :max="2"
              :min="1"
              :step="1"
              show-stops
              style="width: 200px"
              v-model="addRuleData.Priority">
            </el-slider>

          </el-form-item>
        </el-form>

        <div slot="footer">
          <el-button @click=" ()=>mode==='edit' ? submitEdit() : submitAdd()" type="primary">确定</el-button>
          <el-button @click="innerVisible = false">取消</el-button>
        </div>
      </el-dialog>

    </el-dialog>
  </div>
</template>

<script>
  import {
    GetAutoProductionPlanList, //获取排程规则数据
    GetBoardModel, //拼版模板查询
    commitOrderAutoPlan, //提交排产规则设置
    getOrderUnPlanPageList,// 获取订单排产列表
    ModefyAutoProductionPlan,
    AddAutoProductionPlan, GetUnSureLineAndModel
  } from '@/api/order'
  import { GetKMAnd750Line } from '@/api/linebody'
  import Table from './components/orderTable'
  import Table1 from './components/orderRuleTable'
  import { delay } from '@/utils/autoSearch'
  import { ERR_OK } from '@/utils/commons'
  import Pagination from '@/components/Pagination'

  export default {
    name: 'order',
    components: {
      Table,
      Table1,
      Pagination
    },

    data() {
      return {
        // formData:[],
        innerVisible: false,
        search: '',
        value1: '',
        radio: 2,
        checked: '',
        value: '',
        value2: '',
        reset: [],
        TotalNum: 0,
        size: 10,
        currentPage: 1,
        options: [
          {
            value: -1,
            label: '所有'
          },
          {
            value: 0,
            label: '暂停'
          },
          {
            value: 1,
            label: '已下单'
          },
          {
            value: 2,
            label: '正在生产'
          },
          // {
          //     value:3,
          //     label:'完成',
          // },
          {
            value: 4,
            label: '已发货'
          }
        ],
        options1: [
          {
            value: '',
            label: ''
          }
        ],
        options2: [
          {
            value: '',
            label: ''
          }
        ],
        ruleData: [],
        jsonItem: [],
        proDialogVisible: false,
        ruleDialogVisible: false,

        lineData: [],
        boardData: [],
        options3: [
          {
            value: 1,
            label: '1级'
          },
          {
            value: 2,
            label: '2级'
          },
          {
            value: 3,
            label: '3级'
          },
          {
            value: 4,
            label: '4级'
          }
        ],

        addRuleData: {
          OrderAutoPlanName: '',
          LineId: '',
          // LineName: '',
          BoardModelID: '',
          MinNum: 1,
          MaxNum: 1,
          Status: '',
          Priority: ''
        },
        total: 0,
        current: 1,
        limit: 10,

        linebodyData: [],
        boardModelData: [],
        mode: 'add', //  edit
        selectBoardList: [],//  lineId 和 boardId 关系

        searchFormData: {
          LineName: '',
          LineId: '',
          BoardModelID: '',
          PrintStatus: -1
        }

      }
    },
    watch: {
      //用来监听页面变量的改变
      //监听搜索，300ms执行一次fetchData方法（去搜索）
      search() {
        delay(() => {
          this.fetchData()
        }, 300)
      }
    },
    mounted() {
      this.init()

      GetKMAnd750Line({ keyName: '', page: 1, pageSize: 10 }).then(res => {
        if (parseInt(res.Code) === 1) {
          this.linebodyData = res.Result
          this.lineData = res.Result
          console.log(this.lineData, 318)
        }
      })
      GetBoardModel({ PageSize: 999999, PageNum: 1 }).then(res => {
        if (parseInt(res.Code) === 1) {
          this.boardModelData = res.Result.Items
          this.boardData = res.Result.Items
        }
      })
      this.GetAutoProductionPlanList()
    },
    computed: {
      // c() {
      //   return this.ruleData.reduce(([lineIdMap, boardModelIdMap], { LineId, BoardModelID }) => {
      //     let lm = lineIdMap[BoardModelID]
      //     let bm = boardModelIdMap[LineId]
      //     return [
      //       { ...lineIdMap, [BoardModelID]: [...(lm ? lm : []), LineId] },
      //       { ...boardModelIdMap, [LineId]: [...(bm ? bm : []), BoardModelID] }
      //     ]
      //   }, [{}, {}])
      // }
    },
    methods: {

      //  方法也变为了响应式的了
      filterLinebodyData(BoardModelID) {
        //  lid

        const hasSel = this.c[0]
        const hasSelects = hasSel[BoardModelID]
        console.log('hasSel => ', hasSel)
        console.log('BoardModelID => ', BoardModelID)
        console.log('hasSelects => ', hasSelects)
        if (!hasSelects || !BoardModelID) {
          return this.linebodyData
        }
        return this.linebodyData.filter(({ LineId }) => {
          if (LineId === lid) return true
          return !(hasSelects.includes(LineId))
        })
      },
      closeDialog() {
        this.ruleDialogVisible = false
      },
      openEditDialog(data, row) {
        this.mode = 'edit'
        this.addRuleData = { ...row }
        this.innerVisible = true
        this.GetUnSureLineAndModel({ autoProductionId: row.OrderAutoPlanId })
      },
      getCanSelectBoardList({ LineId } = {}) {
        if (!LineId) {
          return this.boardData
        }
        const selectVo = this.selectBoardList.find(s => s.LineId === LineId)
        if (!selectVo) {
          return this.boardData
        }
        console.log('BoardModelVos => %o', selectVo['BoardModelVos'])

        return selectVo['BoardModelVos']
      },
      async GetUnSureLineAndModel({ autoProductionId } = {}) {
        try {
          const { Code, Result } = await GetUnSureLineAndModel({ autoProductionId })
          this.selectBoardList = Result
        } catch (e) {
          console.log(e)
        }
      },
      addRule() {
        this.mode = 'add'
        this.innerVisible = true
        this.GetUnSureLineAndModel({ autoProductionId: 0 })
      },
      // 自动搜索的方法
      async fetchData(val) {
        this.init({ keyName: this.search })
      },
      handleSizeChange(size) {
        this.size = size
        console.log(this.size)
        getOrderUnPlanPageList({
          keyName: this.search,
          status: parseInt(this.value),
          page: 1,
          pageSize: this.size
        }).then(res => {
          if (parseInt(res.Code) === 1) {
            this.reset = res.Result.Items
            this.TotalNum = res.Result.TotalNum
          }
        })
      },
      handleCurrentChange(currentPage) {
        this.currentPage = currentPage
        console.log(currentPage)
        getOrderUnPlanPageList({
          keyName: this.search,
          status: parseInt(this.value),
          page: this.currentPage,
          pageSize: this.size
        }).then(res => {
          if (parseInt(res.Code) === 1) {
            this.reset = res.Result.Items
            this.TotalNum = res.Result.TotalNum
          }
        })
      },
      init() {
        getOrderUnPlanPageList({
          keyName: this.search,
          status: parseInt(this.value),
          page: this.current,
          pageSize: this.size
        }).then(res => {
          if (parseInt(res.Code) === 1) {
            this.reset = res.Result.Items
            this.TotalNum = res.Result.TotalNum
          }
        })
      },

      searchRequest() {
        this.current = 1
        this.GetAutoProductionPlanList()
      },

      GetAutoProductionPlanList({ current = this.current, limit = this.limit } = {}) {

        // {
        //   "OrderAutoPlanId": 0,
        //   "OrderAutoPlanName": "string",
        //   "Status": 0,

        const filterNullV = (o) => {
          return Object.keys(o).reduce((acc, k) => Boolean(o[k]) ? { ...acc, [k]: o[k] } : acc, {})
        }

        GetAutoProductionPlanList({
          PageIndex: current,
          PageSize: limit,
          ...this.searchFormData
        } |> filterNullV).then(res => {
          if (parseInt(res.Code) === 1) {
            this.ruleData = res.Result.Items
            this.total = res.Result.TotalNum
            this.Current = res.Result.CurrentPage
          }
        })
      },

      production() {
        this.proDialogVisible = true
      },
      setrule() {
        this.ruleDialogVisible = true
      },
      //提交
      onSubmit() {
        this.jsonItem = []
        console.log(this.ruleData)
        for (var i = 0; i < this.ruleData.length; i++) {
          var list = {
            OrderAutoPlanId: this.ruleData[i].OrderAutoPlanId,
            Name: this.ruleData[i].Name,
            LineId: this.ruleData[i].LineId,
            MinNum: this.ruleData[i].MinNum,
            MaxNum: this.ruleData[i].MaxNum,
            TargetNum: this.ruleData[i].TargetNum,
            BoardModelID: this.ruleData[i].BoardModelID,
            Status: this.ruleData[i].Status,
            Priority: this.ruleData[i].Priority,
            ProductionPlanConditionPhotoId: this.ruleData[i].ProductionPlanConditionPhotoId
          }
          this.jsonItem.push(list)
        }
        commitOrderAutoPlan({ jsonString: JSON.stringify(this.jsonItem) }).then(res => {
          if (parseInt(res.Code) === 1) {
            this.$message({
              type: 'success',
              message: '成功'
            })
          }
          this.ruleDialogVisible = false
          this.ruleData = []
        })
        // this.ruleData = []
      },
      add3() {
        this.ruleData.push({
          OrderAutoPlanId: 0,
          Name: '',
          LineId: '',
          MinNum: '',
          MaxNum: '',
          BoardModelID: '',
          StatusFormat: '',
          Priority: '',
          ProductionPlanConditionPhotoId: 0
        })
      },

      onSubmit1() {
        this.proDialogVisible = false
      },

      async submitEdit() {
        console.log('submit edit')
        try {
          const { addRuleData } = this
          const {
            OrderAutoPlanId,
            OrderAutoPlanName,
            LineId,
            BoardModelID,
            MinNum,
            MaxNum,
            CommitMaxEmptyNum,
            Priority
          } = addRuleData
          const { Code, Result } = await ModefyAutoProductionPlan({
            OrderAutoPlanId,
            OrderAutoPlanName,
            LineId,
            BoardModelID,
            MinNum,
            MaxNum,
            CommitMaxEmptyNum,
            Priority
          })
          if (Code === ERR_OK) {
            this.$notification.success({ message: '修改计划成功' })
            this.innerVisible = false
            this.ruleData.splice(this.findRuleIdxById(OrderAutoPlanId), 1, Result)
          }
        } catch (e) {
          console.log(e)
          console.log(e.message)
          this.$notification.error({ message: e })

        }
      },

      findRuleIdxById(id) {
        return this.ruleData.findIndex(r => r.OrderAutoPlanId === id)
      },

      async submitAdd() {
        console.log('submitAdd')

        const { Code } = await AddAutoProductionPlan({ ...this.addRuleData })
        if (Code === ERR_OK) {
          this.$message.success('添加成功！')
          this.innerVisible = false
          this.setrule()
        }
      },
      selectLine(val) {
        this.lineData.map((item, index) => {
          if (item.LineId === val) {
            this.addRuleData.LineId = this.lineData[index].LineId
            this.addRuleData.LineName = this.lineData[index].Name
          }
        })
      },
      selectBoard(val) {
        this.boardData.map((item, index) => {
          if (item.BoardModelID === val) {
            this.BoardModelID = this.boardData[index].BoardModelID
          }
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .sizeBig {
    font-size: 16px;
  }

  .topBtn {
    height: 60px;
    width: 98%;
    margin: 0 auto;
    line-height: 60px;
    display: flex;
    justify-content: space-between;

    .icon-set {
      display: inline-block;
      width: 14px;
      height: 14px;
      margin: 0 3px 2px 0;
      background: url("image/shezhi.png") no-repeat;
      vertical-align: middle;
    }

    .icon-hand {
      display: inline-block;
      width: 14px;
      height: 14px;
      margin: 0 3px 2px 0;
      background: url("image/shengchengpaicheng.png") no-repeat;
      vertical-align: middle;
    }
  }

  .message {
    width: 98%;
    margin: 0 auto;
    height: 85px;
    background: rgba(255, 255, 255, 1);
    border: 1px solid rgba(238, 238, 238, 1);
    font-size: 14px;

    .character {
      margin: 20px 0 21px 20px;
      height: 30px;
      line-height: 25px;
      color: #999999;

      .skip {
        color: #0095FF;
        margin-left: 10px;
        cursor: pointer;
      }
    }
  }

  .inputcontent {
    width: 98%;
    margin: 0 auto;
    height: 80px;
    position: relative;
    padding-top: 21px;
    box-sizing: border-box;

    .iconSearch {
      position: absolute;
      left: 16%;
      top: 30px;
      width: 20px;
      height: 20px;
      background-image: url('./image/搜索.png');
      background-repeat: no-repeat;
      cursor: pointer;
    }

    .inSearch {
      float: left;
      width: 18%;
      height: 40px;
    }

    .el-select {
      float: left;
      width: 9%;
      margin-left: 20px;
    }

    .el-button {
      float: left;
      margin-left: 20px;
    }

    .time {
      position: absolute;
      // float: left;
      right: 200px;

      margin-left: 80px;
      width: 290px;
      height: 40px;
      line-height: 40px;

      h4 {
        float: left;
        font-size: 15px;
        font-weight: 600;
      }

      span {
        float: left;
        color: red;
        font-size: 18px;
        font-weight: 700;
      }
    }

    .next {
      float: right;
      height: 40px;
      line-height: 40px;
      margin-right: 40px;

      h4 {
        float: left;
        font-size: 15px;
        font-weight: 600;
      }

      span {
        float: left;
        color: red;
        font-size: 18px;
        font-weight: 700;
      }
    }
  }

  .table {
    width: 98%;
    margin: 0 auto;
  }

  .block {
    text-align: right;
    margin: 28px 20px 0 0;
  }

  .el-dialog {
    width: 100%;
    height: 600px;

    h5 {
      width: 60%;
      margin: 0 auto;
    }

    .el-radio-group {
      width: 17%;
      margin-left: 40%;
      margin-top: 20px;

      .el-radio {
        height: 30px;
        line-height: 30px;
      }
    }

    .botBtn {
      width: 32%;
      margin: 0 auto;
      margin-top: 20px;

      .el-button {
        margin-right: 40px;
      }
    }

    .checkbox {
      margin-left: 380px;
      margin-top: 20px;
    }

  }

  .add {
    width: 50px;
    height: 20px;
    //  border: 1px solid #ccc;
    .skip {
      display: inline-block;


      color: #0095ff;
      margin-left: 10px;
      cursor: pointer;
    }
  }

  .anniu {
    margin-top: 20px;
    margin-left: 340px;

    .fanhui {
      margin-right: 30px;
    }
  }
</style>
